const Model = require("../../models");
const { USER_TYPES } = require("../../sys_config");
const { cryto, uuid } = require("../../utils");

module.exports = {
  name: "user",

  async join(data) {
    try {
      const model = Model.models.user;
      const salt = uuid();
      const password = cryto(data.password, salt);
      const joined = (await model.get_user_of_phone(data.phone)) !== null;
      if (joined) {
        return { ok: 0, err: "用户已存在" };
      }
      await model.core.create({ ...data, password, uuid: salt });
      return { ok: 1 };
    } catch (e) {
      console.log(e);
      return { ok: 0 };
    }
  },

  async login(data) {
    try {
      const user_model = Model.models.user;
      const user = await user_model.get_user_of_phone(data.phone);
      if (user === null) {
        return { ok: 0, err: "用户不存在" };
      }
      if (user.type === USER_TYPES.DOCTOR) {
        const d_info = await Model.models.doctor_info.core.findOne({
          where: { u_id: user.id },
        });
        if (d_info && !d_info.enable) {
          return { ok: 0, err: "你账号已禁用 请联系管理员恢复!" };
        }
      }
      const password = cryto(data.password, user.uuid);
      if (password === user.password) {
        let data = await user_model.remove_sensitive(user);
        return { ok: 1, data };
      }
      return { ok: 0, err: "账号或密码错误" };
    } catch (e) {
      console.log(e);
      return { ok: 0 };
    }
  },

  async del(query) {
    try {
      await Model.models.user.core.destroy({ where: query });
      return { ok: 1 };
    } catch (e) {
      console.log(e);
      return { ok: 0 };
    }
  },
};
